import Base64 from "base-64";

// 日期格式化
export const formatDate = (date, format = 'YYYY-MM-DD HH:mm:ss') => {
	if (!date) return ''
	if (!(date instanceof Date)) {
		date = new Date(date)
	}

	const year = date.getFullYear()
	const month = String(date.getMonth() + 1).padStart(2, '0')
	const day = String(date.getDate()).padStart(2, '0')
	const hours = String(date.getHours()).padStart(2, '0')
	const minutes = String(date.getMinutes()).padStart(2, '0')
	const seconds = String(date.getSeconds()).padStart(2, '0')

	return format
		.replace('YYYY', year)
		.replace('MM', month)
		.replace('DD', day)
		.replace('HH', hours)
		.replace('mm', minutes)
		.replace('ss', seconds)
}

// 数字千分位格式化
export const formatNumber = (num) => {
	if (typeof num !== 'number') return num
	return num.toLocaleString('zh-CN')
}

// 防抖函数
export const debounce = (func, delay = 300) => {
	let timer = null
	return function(...args) {
		if (timer) clearTimeout(timer)
		timer = setTimeout(() => {
			func.apply(this, args)
		}, delay)
	}
}

// 节流函数
export const throttle = (func, interval = 300) => {
	let lastTime = 0
	return function(...args) {
		const now = Date.now()
		if (now - lastTime >= interval) {
			func.apply(this, args)
			lastTime = now
		}
	}
}

// 深拷贝
export const deepClone = (obj) => {
	if (obj === null || typeof obj !== 'object') return obj
	let cloneObj = Array.isArray(obj) ? [] : {}
	for (let key in obj) {
		if (obj.hasOwnProperty(key)) {
			cloneObj[key] = deepClone(obj[key])
		}
	}
	return cloneObj
}

// 验证工具
export const validator = {
	isMobile: (value) => /^1[3-9]\d{9}$/.test(value),
	isEmail: (value) => /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(value),
	isIdCard: (value) => /(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(value),
	isPassword: (value) => /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/.test(value),
	isEmpty: (value) => value === null || value === undefined || value === ''
}

//显示消息提示框
export const showToast = (title, icon = "none") => {
	uni.showToast({
		title,
		icon,
	});
}

//显示 loading 提示框
export const showLoading = (title, icon = "none") => {
	uni.showLoading({
		title,
	});
}

//关闭 loading 提示框
export const hideLoading = () => {
	uni.hideLoading();
}

//调用某组件内方法
export const someMethod = (Vue, refName, method, params) => {
	Vue.$nextTick(() => {
		Vue.$refs[refName][method](params);
	});
}

//将字符串先utf-8编码，再转base64
export const utf8ToBase64 = (str) => {
	return Base64.encode(unescape(encodeURIComponent(str)))
}

//将字符串先解码
export const deutf8ToBase64 = (str) => {
	return decodeURIComponent(escape(Base64.decode(str)));
}

//将对象带添加原值
export const setOriginal = (obj) => {
	if (obj === null || typeof obj !== 'object' || Array.isArray(obj)) return obj
	let originalObj = {}
	for(let key in obj) {
		originalObj[key] = obj[key];
		originalObj[`${key}_Original`] = obj[key];
	}
	return originalObj;
}

//浮点型相加
export const accAdd = (arg1, arg2) => {
	var r1, r2, m;
	try { r1 = arg1.toString().split(".")[1].length } catch (e) { r1 = 0 }
	try { r2 = arg2.toString().split(".")[1].length } catch (e) { r2 = 0 }
	m = Math.pow(10, Math.max(r1, r2))
	return (arg1 * m + arg2 * m) / m
}

//浮点型相减
export const accSub = (arg1, arg2) => {
	return accAdd(arg1, -arg2);
}

//浮点型相乘
export const accMul = (arg1, arg2) => {
	let m = 0, s1 = arg1.toString(), s2 = arg2.toString();
	try { m += s1.split(".")[1].length } catch (e) { }
	try { m += s2.split(".")[1].length } catch (e) { }
	return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m)
}

//浮点型相除
export const accDiv = (arg1, arg2) => {
	var t1 = 0, t2 = 0, r1, r2;
	try { t1 = arg1.toString().split(".")[1].length; } catch (e) { t1 = 0; }
	try { t2 = arg2.toString().split(".")[1].length; } catch (e) { t2 = 0; }
	r1 = Number(arg1.toString().replace(".", ""));
	r2 = Number(arg2.toString().replace(".", ""));
	return accMul(r1 / r2, Math.pow(10, t2 - t1));
}